package com.guigu.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.guigu.eduservice.dto.MonthlyStatsDTO;
import com.guigu.eduservice.entity.Equipment;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guigu.eduservice.dto.OrderListDTO;
import com.guigu.eduservice.dto.OrderQueryDTO;
import com.guigu.eduservice.entity.EquipmentImage;
import com.guigu.eduservice.entity.Order;
import com.guigu.eduservice.entity.User;
import com.guigu.eduservice.mapper.EquipmentImageMapper;
import com.guigu.eduservice.mapper.EquipmentMapper;
import com.guigu.eduservice.mapper.OrderMapper;
import com.guigu.eduservice.mapper.UserMapper;
import com.guigu.eduservice.service.EquipmentService;
import com.guigu.eduservice.service.OrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import com.guigu.eduservice.vo.OrderVo;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表（存储买卖双方的交易订单信息） 服务实现类
 * </p>
 *
 * @author janecraft
 * @since 2025-09-27
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private EquipmentService equipmentService;
    @Autowired
    private EquipmentMapper equipmentMapper;
    @Autowired
    private EquipmentImageMapper equipmentImageMapper;
    //根据用户ID，订单状态，以及时间查询订单，并且将设备塞给订单
    @Override
    public List<Order> selectOrderByUId(OrderVo vo) {
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();

        // 1. 用户ID筛选
        if (vo.getUserId() != null) {
            wrapper.eq(Order::getBuyerId, vo.getUserId());
        }

        // 2. 订单状态筛选
        if (vo.getOrderStatus() != null) {
            wrapper.eq(Order::getOrderStatus, vo.getOrderStatus());
        }

        // 3. 时间范围筛选（核心优化部分）
        // 先判断两个时间是否都不为null，再比较大小
        if (vo.getStartTime() != null && vo.getEndTime() != null) {
            // 确保结束时间不早于开始时间
            if (vo.getEndTime().isAfter(vo.getStartTime()) || vo.getEndTime().equals(vo.getStartTime())) {
                wrapper.between(Order::getCreateTime, vo.getStartTime(), vo.getEndTime());
            } else {
                // 可选：如果结束时间早于开始时间，可抛出异常或交换时间
                throw new IllegalArgumentException("结束时间不能早于开始时间");
                // 或者：交换时间范围
                // wrapper.between(Order::getCreateTime, vo.getEndTime(), vo.getStartTime());
            }
        } else if (vo.getStartTime() != null) {
            // 只有开始时间：查询>=开始时间的记录
            wrapper.ge(Order::getCreateTime, vo.getStartTime());
        } else if (vo.getEndTime() != null) {
            // 只有结束时间：查询<=结束时间的记录
            wrapper.le(Order::getCreateTime, vo.getEndTime());
        }

        // 4. 查询订单列表
        List<Order> orders = orderMapper.selectList(wrapper);

        // 5. 关联查询设备信息
        for (Order order : orders) {
            Equipment equipment = equipmentService.getByIdImageV(order.getEquipmentId());
            order.setEquipment(equipment);
        }
        return orders;
    }
    @Autowired
    private UserMapper userMapper;

    /**
     * 订单列表查询
     * @param query
     * @return
     */
    @Override
    public PageInfo<Order> getOrderList(OrderQueryDTO query) {
        QueryWrapper<Order> orderWrapper = new QueryWrapper<>();

        // 时间范围筛选
        if (query.getStartTime() != null) {
            orderWrapper.ge("create_time", query.getStartTime());
        }
        if (query.getEndTime() != null) {
            orderWrapper.le("create_time", query.getEndTime());
        }

        // 订单号筛选
        if (query.getOrderNo() != null) {
            orderWrapper.like("order_id", query.getOrderNo());
        }

        // 状态筛选：仅当orderStatus不为null时，才添加状态条件
        if (query.getOrderStatus() != null) {
            orderWrapper.eq("order_status", query.getOrderStatus());
        }
        // 按创建时间倒序
        orderWrapper.orderByDesc("create_time");

        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        List<Order> orderList = orderMapper.selectList(orderWrapper);

        for (Order order : orderList){
            Equipment equipment = equipmentMapper.selectById(order.getEquipmentId());
            order.setEquipment(equipment);
            Long equipmentId = equipment.getEquipmentId();
            LambdaQueryWrapper<EquipmentImage> imageLambdaQueryWrapper = new LambdaQueryWrapper<>();
            if (equipmentId != null){
                imageLambdaQueryWrapper.eq(EquipmentImage::getEquipmentId, equipmentId);
                List<EquipmentImage> images = equipmentImageMapper.selectList(imageLambdaQueryWrapper);
                order.setEquipmentImages(images);
            }
        }
        return new PageInfo<>(orderList);
    }

    @Override
    public boolean updateOder(OrderQueryDTO dto) {
        String orderNo = dto.getOrderNo();
        if (orderNo != null) {
            Order order = orderMapper.selectOne(new QueryWrapper<Order>().eq("order_id", orderNo));
            if (order != null) {
                order.setLogisticsCompany("顺丰");
                // 生成物流单号
                order.setLogisticsNo(String.valueOf(System.currentTimeMillis()));
                order.setOrderStatus(dto.getOrderStatus());
                order.setUpdateTime(LocalDateTime.now());
                order.setReceiptTime(LocalDateTime.now());
                return orderMapper.updateById(order) > 0;
            }
        }
        return false;
    }

    /**
     * 订单数据统计
     * @return
     */
    @Override
    public List<MonthlyStatsDTO> getDashboardStats() {
        return orderMapper.getMonthlyTransactionAmount();
    }

    @Override
    public int getTodayPaidOrderCount() {
        return orderMapper.getTodayPaidOrderCount();
    }

    @Override
    public BigDecimal getTodayPaidAmount() {
        return orderMapper.getTodayPaidAmount();
    }


    /**
     * 订单列表数据转换
     * @param order
     * @return
     */
    private OrderListDTO convertToDTO(Order order) {
        OrderListDTO dto = new OrderListDTO();
        dto.setOrderNo(String.valueOf(order.getOrderId()));
        // 设备标题拼接列如（出售2022年中联66米泵车）
        if (order.getEquipmentId() != null) {
            // 这里需要根据实际的Equipment实体类结构调整
             Equipment equipment = equipmentMapper.selectById(order.getEquipmentId());
             String title = "出售" + equipment.getYear() + "年" + equipment.getBrand() + equipment.getModel();
             dto.setEquipmentTitle(title);
        }
        // 设备源编号
        dto.setEquipmentNo(String.valueOf(order.getEquipmentId()));
        // 实际付款
        dto.setActualPay(order.getDepositAmount().add(order.getBalanceAmount()));
        // 买家信息
        // 用户名(ID)
        if (order.getBuyerId() != null) {
            User user = userMapper.selectById(order.getBuyerId());
            dto.setBuyerName(user.getUserName() + "(" + user.getUserId() + ")");
        }
        // 支付方式
        dto.setPayMethod(order.getPaymentMethod());

        dto.setCreateTime(order.getCreateTime());
        dto.setOrderStatus(order.getOrderStatus());
        dto.setOrderAmount(order.getOrderAmount());
        return dto;
    }

}
